﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace CraigsCrawler
{
    [DataContract]
    public partial class SearchStorage : NamedThing
    {
        string directory;
        string filename;

        [DataMember]
        public string query;

        [DataMember]
        public TimeSpan queryInterval;

        [DataMember]
        public string[] cities;

        [DataMember]
        public List<Entry> entries;

        [DataMember]
        public List<Tuple<string, string>> suppressedTitles;

        public Dictionary<string, Entry> entriesByUrl;

        [OnDeserialized]
        public void OnDeserialized(StreamingContext c)
        {
            entriesByUrl = new Dictionary<string, Entry>(entries.ToDictionary(e => e.link, e => e));
            Querier.QueryInterval = queryInterval;
            foreach (Entry entry in entries)
            {
                entry.parent = this;
            }
        }
    }

    [DataContract]
    public class Entry
    {
        public Entry(SearchStorage parent)
        {
            this.parent = parent;
        }

        public SearchStorage parent;

        [DataMember]
        public string link;

        [DataMember]
        public string title;

        [DataMember]
        public string city;

        [DataMember]
        public string thumbnail;

        [DataMember]
        public DateTime posted;

        [DataMember]
        public EntryState entryState;

        [DataMember]
        public DateTime lastRetrieved;

        public EntryControl control;
    }

    public enum EntryState
    {
        New,
        ManuallyIgnored,
        AutomaticallyIgnored,
        Interested
    }

    public class EntryStateComparer_RelevantFirst : IComparer<EntryState>
    {
        public int Compare(EntryState x, EntryState y)
        {
            return Val(x).CompareTo(Val(y));
        }

        private int Val(EntryState input)
        {
            switch (input)
            {
                default:
                case EntryState.New: return 0;
                case EntryState.ManuallyIgnored: return -2;
                case EntryState.AutomaticallyIgnored: return -1;
                case EntryState.Interested: return 1;
            }
        }
    }
}
